<template>
  <div class="review-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">评论管理</h2>
      <p class="page-desc">管理用户的所有产品评论，支持删除功能</p>
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <div class="filter-container">
        <el-input
          v-model="searchText"
          placeholder="搜索评论内容/商品ID"
          prefix-icon="el-icon-search"
          class="search-input"
          @keyup.enter.native="handleSearch"
        ></el-input>
      </div>
    </div>

    <!-- 评论列表 -->
    <el-table
      :data="filteredReviews"
      border
      stripe
      style="width: 100%; background: #fff; border-radius: 8px; margin-bottom: 20px;"
      v-loading="loading"
    >
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
      ></el-table-column>

      <el-table-column
        prop="user_name"
        label="用户名"
        width="120"
        align="center"
      ></el-table-column>

      <el-table-column
        prop="product_id"
        label="产品ID"
        width="100"
        align="center"
      ></el-table-column>

      <el-table-column
        prop="product_type"
        label="产品类型"
        width="120"
        align="center"
      ></el-table-column>

      <!-- 评分列 - 优化显示 -->
      <el-table-column
        prop="rating"
        label="评分"
        width="160"
        align="center"
      >
        <template slot-scope="scope">
          <div class="rating-display">
            <div class="rating-stars">
              <i
                v-for="star in 5"
                :key="star"
                class="el-icon-star"
                :style="{ color: star <= scope.row.rating ? '#F9A826' : '#E0E0E0' }"
              ></i>
            </div>
            <span class="rating-value">{{ scope.row.rating || 0 }}.0</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        prop="content"
        label="评论内容"
        min-width="300"
      ></el-table-column>

      <el-table-column
        label="评论时间"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.created_at) }}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            class="delete-btn"
            @click="showDeleteConfirm(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <div v-if="filteredReviews.length === 0 && !loading" class="empty-state">
      <i class="el-icon-comment"></i>
      <p>暂无评论数据</p>
    </div>

    <!-- 分页 -->
    <div v-if="filteredReviews.length > 0" class="pagination">
      <el-pagination
        layout="prev, pager, next, total"
        :total="pagination.total"
        :page-size="pagination.limit"
        :current-page.sync="pagination.page"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>

    <!-- 删除确认弹窗 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="300px"
      :close-on-click-modal="false"
    >
      <p>确定要删除此评论吗？此操作不可撤销。</p>
      <div slot="footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import api from '@/api/request'

export default {
  name: 'ProductReview',
  data() {
    return {
      // 评论数据
      reviews: [],
      loading: false,

      // 筛选条件
      searchText: '',
      pagination: {
        page: 1,
        limit: 10,
        total: 0
      },

      // 弹窗状态
      deleteDialogVisible: false,
      reviewIdToDelete: null
    }
  },
  computed: {
    // 筛选后的评论列表
    filteredReviews() {
      return this.reviews.filter(review => {
        // 搜索筛选
        if (this.searchText) {
          const searchLower = this.searchText.toLowerCase()
          // 检查是否匹配商品ID、评论内容或评分
          return (review.content && review.content.toLowerCase().includes(searchLower)) ||
                 (review.product_id && review.product_id.toString().toLowerCase().includes(searchLower)) ||
                 (review.rating && review.rating.toString().includes(searchLower))
        }
        return true
      })
    }
  },
  created() {
    // 页面加载时获取评论数据
    this.fetchReviews()
  },
  methods: {
    // 格式化日期时间为 "YYYY-MM-DD HH:MM" 格式
    formatDateTime(dateString) {
      if (!dateString) return '';

      // 处理不同格式的时间字符串
      const date = new Date(dateString);

      // 检查日期是否有效
      if (isNaN(date.getTime())) return dateString;

      // 提取年、月、日
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');

      // 提取小时、分钟
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      // 组合成目标格式
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 获取评论数据
    async fetchReviews() {
      this.loading = true;
      try {
        // 调用管理员接口获取所有评论
        const response = await api.get('/reviews/admin', {
          params: {
            page: this.pagination.page,
            limit: this.pagination.limit
          }
        });

        console.log('后端原始响应:', response);
        console.log('评论数据:', response.data.reviews);

        if (response.code === 200) {
          this.reviews = response.data.reviews;
          this.pagination.total = response.data.pagination.total;
        } else {
          this.$message.error('获取评论失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('获取评论出错:', error);
        this.$message.error('获取评论失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    // 搜索处理
    handleSearch() {
      this.pagination.page = 1;
      this.fetchReviews();
    },

    // 分页变化处理
    handlePageChange(page) {
      this.pagination.page = page;
      this.fetchReviews();
    },

    // 显示删除确认
    showDeleteConfirm(id) {
      this.reviewIdToDelete = id;
      this.deleteDialogVisible = true;
    },

    // 确认删除
    async confirmDelete() {
      try {
        const response = await api.delete(`/reviews/admin/${this.reviewIdToDelete}?delete_images=true`);

        if (response.code === 200 ) {
          this.$message.success('评论已删除');
          // 重新获取评论列表
          this.fetchReviews();
          this.deleteDialogVisible = false;
        } else {
          this.$message.error('删除失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('删除评论出错:', error);
        this.$message.error('删除评论失败，请稍后重试');
      }
    }
  }
}
</script>

<style scoped>
/* 评分显示样式优化 */
.rating-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.rating-stars {
  display: flex;
  font-size: 16px;
}

.rating-value {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

/* 其他原有样式保持不变 */
.page-header {
  margin-bottom: 20px;
}

.page-title {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #303133;
}

.page-desc {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 20px;
  color: #c0c4cc;
}

/* 分页样式修改 - 居中显示 */
.pagination {
  text-align: center; /* 核心：将分页控件居中 */
  margin-top: 20px;
  margin-bottom: 30px;
}

/* 确保Element UI分页组件在居中容器内正确显示 */
.pagination /deep/ .el-pagination {
  display: inline-flex;
  justify-content: center;
}

.delete-btn {
  color: #F56C6C;
}
</style>

